package com.easytouch.core.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 * Created by gulin on 2016/9/13.
 */
public class MD5 {

    private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * MD5加密
     *
     * @param msg 要加密的串
     * @return
     */
    public static String md5Encode(String msg) {
        String result;
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] md5Bytes = digest.digest(msg.getBytes("UTF-8"));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < md5Bytes.length; i++) {
                int val = md5Bytes[i] & 0xff;
                if (val < 16) {
                    builder.append("0");
                }
                builder.append(Integer.toHexString(val));
            }
            result = builder.toString();
        } catch (NoSuchAlgorithmException e) {
            result = "";
        } catch (UnsupportedEncodingException e) {
            result = "";
        }
        return result;
    }

    /**
     * 生成文件的md5校验值
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static String getFileMD5String(File file) throws IOException {
        if(!file.exists())
        {
            return "";
        }
        MessageDigest messagedigest;
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        }catch (NoSuchAlgorithmException e) {
            return "";
        }
        InputStream fis;
        fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        int numRead = 0;
        while ((numRead = fis.read(buffer)) > 0) {
            messagedigest.update(buffer, 0, numRead);
        }
        fis.close();
        return bufferToHex(messagedigest.digest());
    }

    /**
     * 求字节数组MD5
     * @param data 字节数组
     * @return MD5值
     */
    public static String getBytesMD5(byte[] data)
    {
        MessageDigest messagedigest;
        try {
            messagedigest = MessageDigest.getInstance("MD5");
        }catch (NoSuchAlgorithmException e) {
            return "";
        }
        messagedigest.update(data);
        return bufferToHex(messagedigest.digest());
    }

    private static String bufferToHex(byte bytes[]) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static String bufferToHex(byte bytes[], int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;
        for (int l = m; l < k; l++) {
            appendHexPair(bytes[l], stringbuffer);
        }
        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换, >>> 为逻辑右移，将符号位一起右移,此处未发现两种符号有何不同
        char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }
}
